using System.Collections.Generic;
using System.Linq;
using Nekonya.Dicts;
using Nekonya.Managers.Bag;
using UnityEngine;

namespace Nekonya.Managers
{
    /// <summary>
    /// 背包管理器 （本质上数据层）
    /// </summary>
    public class BagManager
    {
        private List<BagItem> m_BagItems = new List<BagItem>();

        private ItemDict m_ItemDict;

        public BagManager(DictFactory dictFactory)
        {
            m_ItemDict = dictFactory.GetDict<ItemDict>();
        }


        public IEnumerable<BagItem> GetAll()
        {
            return m_BagItems.ToArray();
        }

        /// <summary>
        /// 添加道具
        /// </summary>
        /// <param name="itemId">道具ID</param>
        /// <param name="num">道具数量</param>
        /// <returns></returns>
        public BagItem AddItem(int itemId, uint num = 1)
        {
            var itemTpl = m_ItemDict.Get(itemId);

            var bagItem = m_BagItems.FirstOrDefault(bi => bi.Id == itemId);
            if(bagItem != null)
            {
                bagItem.Number += num;
                Debug.LogFormat("[背包管理器]添加道具 {0} ({1}个), 现总数{2}个", m_ItemDict.GetName(itemTpl), num, bagItem.Number);
                return bagItem;
            }
            else
            {
                bagItem = new BagItem
                {
                    Id = itemId,
                    Number = num
                };
                m_BagItems.Add(bagItem);
                Debug.LogFormat("[背包管理器]添加道具 {0} ({1}个), 现总数{2}个", m_ItemDict.GetName(itemTpl), num, bagItem.Number);
                return bagItem;
            }
        }
    }
}
